package com.cardbaobao.cardbabyclient.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.cardbaobao.cardbabyclient.R;

/**
 * 拐角ImageView
 * Created by zad
 * 2016/11/4 15:59
 */

public class CornerImageView extends ImageView {

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    /**
     * 圆角半径
     */
    private int mRoundRadius = 20;

    public CornerImageView(Context context) {
        this(context, null);
    }

    public CornerImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CornerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CornerImageView);
        mRoundRadius = (int) a.getDimension(R.styleable.CornerImageView_cornerRadius,mRoundRadius);
        a.recycle();
    }

    /**
     * 绘制圆角矩形图片
     * @author caizhiming
     */
    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (null != drawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            Bitmap b = getRoundBitmap(bitmap, mRoundRadius);
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0,0,getWidth(),getHeight());
            mPaint.reset();
            canvas.drawBitmap(b, rectSrc, rectDest, mPaint);
        } else {
            super.onDraw(canvas);
        }
    }

    /**
     * 获取圆角矩形图片方法
     * @param bitmap
     * @param roundRadius 圆角半径
     * @return Bitmap
     */
    private Bitmap getRoundBitmap(Bitmap bitmap, int roundRadius) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);//空白图片生成画布背景

        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);//Rect转换成RectF
        canvas.drawARGB(0, 0, 0, 0);
        mPaint.setColor(0xff424242);
        canvas.drawRoundRect(rectF, roundRadius, roundRadius, mPaint);//绘制圆角矩阵
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//图层叠加
        canvas.drawBitmap(bitmap, rect, rect, mPaint);//绘制图片
        return output;
    }
}
